package study.dq.jms.p2p;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dongqun
 * @version 1.0
 * @description 类的功能描述
 * @date 2019/10/18 18:15
 */
public class Producter {
    private QueueSession session;
    private AtomicInteger count = new AtomicInteger(0);
    private ThreadLocal<MessageProducer> threadLocal = new ThreadLocal<>();
    public Producter(String username,String password,String borkerUrl){
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(username,password,borkerUrl);
            QueueConnection connection = ((ActiveMQConnectionFactory) factory).createQueueConnection();
            connection.start();
            session = connection.createQueueSession(true,Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String disname){
        try {
            Queue queue = session.createQueue(disname);
            QueueSender sender;
            if (threadLocal.get()!=null){
                sender = (QueueSender) threadLocal.get();
            }else{
                sender = session.createSender(queue);
                threadLocal.set(sender);
            }
//            while (true){
                Thread.sleep(1000);
                int num = count.getAndIncrement();
                TextMessage textMessage = session.createTextMessage(Thread.currentThread().getName()+"我是大帅哥，我现在正在生产东西！,count:"+num);
                System.out.println(Thread.currentThread().getName()+"我是大帅哥，我现在正在生产东西！,count:"+num);
                sender.send(textMessage);
                session.commit();
//            }
        } catch (JMSException | InterruptedException e) {
            e.printStackTrace();
        }

    }
}
